package com.cn.xiaonuo.tcrfinance.tcrshops.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.xiaonuo.common.constant.Status;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.common.utils.DateUtils;
import com.cn.xiaonuo.common.utils.GetJavaTypeConvert;
import com.cn.xiaonuo.common.utils.OrderNumGeneration;
import com.cn.xiaonuo.common.utils.payutils.LakalaPayCommon;
import com.cn.xiaonuo.common.utils.payutils.LakalaPayUtil;
import com.cn.xiaonuo.core.factory.PageFactory;
import com.cn.xiaonuo.core.pojo.response.ResponseData;
import com.cn.xiaonuo.dbs.core.annotation.DataSource;
import com.cn.xiaonuo.sys.modular.consts.entity.NSysConfig;
import com.cn.xiaonuo.sys.modular.consts.mapper.NSysConfigMapper;
import com.cn.xiaonuo.tcrfinance.sysmgmt.entity.SysUserHpcEntity;
import com.cn.xiaonuo.tcrfinance.sysmgmt.mapper.SysUserHpcMapper;
import com.cn.xiaonuo.tcrfinance.tcrgnete.mapper.ShopSettlementMapper;
import com.cn.xiaonuo.tcrfinance.tcrorder.entity.*;
import com.cn.xiaonuo.tcrfinance.tcrorder.mapper.PvOrderMapper;
import com.cn.xiaonuo.tcrfinance.tcrorder.mapper.PvPossessionGoodsMapper;
import com.cn.xiaonuo.tcrfinance.tcrorder.mapper.PvPossessionGoodsRewardMapper;
import com.cn.xiaonuo.tcrfinance.tcrorder.mapper.PvReleaseBaseMapper;
import com.cn.xiaonuo.tcrfinance.tcrorder.param.ReflectRecordParam;
import com.cn.xiaonuo.tcrfinance.tcrorder.service.StorageRecordService;
import com.cn.xiaonuo.tcrfinance.tcrshops.entity.*;
import com.cn.xiaonuo.tcrfinance.tcrshops.mapper.*;
import com.cn.xiaonuo.tcrfinance.tcrshops.param.*;
import com.cn.xiaonuo.tcrfinance.tcrshops.service.PlatformService;
import com.cn.xiaonuo.tcrfinance.tcrusers.entity.PvLoginUser;
import com.cn.xiaonuo.tcrfinance.tcrusers.entity.PvWallet;
import com.cn.xiaonuo.tcrfinance.tcrusers.entity.PvWalletLog;
import com.cn.xiaonuo.tcrfinance.tcrusers.mapper.PvLoginUserMapper;
import com.cn.xiaonuo.tcrfinance.tcrusers.mapper.PvWalletLogMapper;
import com.cn.xiaonuo.tcrfinance.tcrusers.mapper.PvWalletMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class PlatformServiceImpl extends ServiceImpl<PvShopMapper, PvShop> implements PlatformService {
    private static final Logger log = LoggerFactory.getLogger(PlatformServiceImpl.class);
    @Autowired
    private PvShopMapper pvShopMapper;
    @Autowired
    private PlatformMapper platformDao;
    @Autowired
    private PvDeliveryAddMapper pvDeliveryAddMapper;
    @Autowired
    private PvOrderMapper pvOrderMapper;
    @Autowired
    private PvPossessionGoodsRewardMapper pvPossessionGoodsRewardMapper;
    @Autowired
    private SysUserHpcMapper sysUserHpcMapper;
    @Autowired
    private PvLoginUserMapper pvLoginUserMapper;
    @Autowired
    private PvOrderRefundMapper pvOrderRefundMapper;
    @Autowired
    private PvOrderDeliveryMapper pvOrderDeliveryMapper;
    @Autowired
    private PvOrderRefundLogMapper pvOrderRefundLogMapper;
    @Autowired
    private PvOrderDeliveryLogMapper pvOrderDeliveryLogMapper;
    @Autowired
    private PvPossessionGoodsMapper pvPossessionGoodsMapper;
    @Autowired
    private PvReleaseBaseMapper pvReleaseBaseMapper;
    @Autowired
    private NSysConfigMapper nSysConfigMapper;
    @Autowired
    private PvReleaseBaseLogMapper pvReleaseBaseLogMapper;
    @Autowired
    private PvWalletMapper pvWalletMapper;
    @Autowired
    private PvWalletLogMapper pvWalletLogMapper;
    @Autowired
    private PvProductMapper pvProductMapper;
    @Autowired
    private StorageRecordService storageRecordService;

    @Override
    public BusinessMessage queryShopList(PvShopReqParam pvShopReqParam) {
        BusinessMessage<Object> message = new BusinessMessage<>();
        Page page = PageFactory.defaultPage();
        PvShop pvShop = new PvShop();
        BeanUtil.copyProperties(pvShopReqParam, pvShop);
        // 设置分页参数
        PageHelper.startPage((int) page.getCurrent(), (int) page.getSize());
        // 设置分页参数
        List<Map<String, Object>> lists = platformDao.queryShopList(pvShop);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(lists);
        message.setCode("200");
        message.setData(pageInfo);
        message.setSuccess(true);
        message.setMessage("操作成功");
        return message;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BusinessMessage addShop(PvShopParam pvShopParam) {
        PvShop pvShop = BeanUtil.copyProperties(pvShopParam, PvShop.class);
        pvShop.setCreatedAt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        if (getPvShopByPhone(pvShopParam.getPhone())) {
            return BusinessMessage.fail("电话号码不能重复");
        }
        if (!this.save(pvShop)) {
            return BusinessMessage.fail("添加商家失败");
        }

        return BusinessMessage.success();
    }


    @Override
    public BusinessMessage updateShop(PvShopParam pvShopParam) {
        BusinessMessage<Object> message = new BusinessMessage<>();
        PvShop pvShop = pvShopMapper.selectById(pvShopParam.getId());
        boolean flag = false;
        if (StringUtils.isNotBlank(pvShop.getPhone())) {
            if (!(pvShop.getPhone().equals(pvShopParam.getPhone()))) {//判断手机号码是否相等
                flag = true;
            }
        }
        if (flag) {//如果手机号码不等，判断该手机号码是否存在
            boolean phoneFlag = getPvShopByPhone(pvShopParam.getPhone());
            if (phoneFlag) {
                message.setMessage("电话号码不能重复");
                message.setSuccess(false);
                message.setCode("-1");
                return message;
            }
        }
        BeanUtil.copyProperties(pvShopParam, pvShop);
        int i = pvShopMapper.updateById(pvShop);
        if (i > 0) {
            message.setMessage("修改商家信息成功");
            message.setSuccess(true);
            message.setData(i);
            message.setCode("200");
            return message;
        }
        message.setMessage("修改商家信息失败");
        message.setSuccess(true);
        message.setCode("-1");
        return message;
    }

    @Override
    public BusinessMessage selectOrderLogisticsByself(Map<String, Object> params) {
        BusinessMessage message = new BusinessMessage();
        try {
            String jk_status = GetJavaTypeConvert.getString(params.get("jk_status"));//结算状态:0：未结算 1:已结算
            Integer deliveryStatus = GetJavaTypeConvert.getInteger(params.get("deliveryStatus"));//物流状态:0.全部1:未发货2.已发货3.已收货
            String serialNumber = GetJavaTypeConvert.getString(params.get("serialNumber"));//订单编号
            Integer shopId = GetJavaTypeConvert.getInteger(params.get("shopId"));//商铺id
            Integer salesMode = GetJavaTypeConvert.getInteger(params.get("salesMode"));//销售模式
            Integer pageSize = (Integer) params.get("pageSize");
            Integer pageNum = (Integer) params.get("pageNo");
            if (null == pageNum || Integer.valueOf(pageNum) <= 1) {
                pageNum = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            Long beginTime = GetJavaTypeConvert.getLong(params.get("beginTime"));
            Long endTime = GetJavaTypeConvert.getLong(params.get("endTime"));
            String begin = null;
            String end = null;
            if (null != beginTime && null != endTime) {
                Map<String, String> map = new HashMap<>(16);
                map = DateUtils.conversionTime(beginTime, endTime);
                begin = map.get("begin");
                end = map.get("end");
            }
            PageHelper.startPage(pageNum, pageSize);
            List<Map<String, Object>> resultList = platformDao.selectOrderLogisticsByself(jk_status, deliveryStatus, serialNumber, begin, end, shopId, salesMode);
            if (resultList.size() >= 0) {
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
                message.setData(pageInfo);
                message.setSuccess(true);
                message.setMessage("请求成功");
                message.setCode("200");
            } else {
                message.setMessage("无数据");
                message.setSuccess(false);
                message.setCode("-1");
            }
        } catch (Exception e) {
            message.setMessage("请求失败");
            message.setSuccess(false);
            message.setCode("-1");
            e.printStackTrace();
        }
        return message;
    }

    @Override
    public BusinessMessage updateOrderLogisticsByselfStatus(Map<String, Object> params) {
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String format = formatter.format(date);
        BusinessMessage message = new BusinessMessage();
        try {
            Integer deliveryId = (Integer) params.get("deliveryId");
            String logisticsNum = (String) params.get("logisticsNum");
            String logisticsType = (String) params.get("logisticsType");
            PvDeliveryAdd deliveryAdd = pvDeliveryAddMapper.selectById(deliveryId);//获取用户地址
            if (null != deliveryAdd) {
                PvOrder pvOrder = pvOrderMapper.selectById(deliveryAdd.getGoodLogId());
                PvLoginUser loginUser = pvLoginUserMapper.selectById(pvOrder.getPickUserId());
                if (loginUser.getUserType()==1){
                    message.setMessage("体验用户订单不可发货!");
                    message.setSuccess(false);
                    message.setCode("-1");
                    return message;
                }
                deliveryAdd.setLogisticsNum(logisticsNum);
                deliveryAdd.setLogisticsStatus("2");
                deliveryAdd.setLogisticsType(logisticsType);
                deliveryAdd.setId(deliveryId);
                if (deliveryAdd.getDeliverTime() == null) {
                    deliveryAdd.setDeliverTime(format);
                }
                deliveryAdd.setUpdateTime(new Date());
                pvDeliveryAddMapper.updateById(deliveryAdd);
                if (pvOrder != null) {
                    pvOrder.setLogisticsStatus(2);
                    pvOrder.setUpdatedAt(date);
                    pvOrderMapper.updateById(pvOrder);
                }
                storageRecordService.updateStorageRecord(Convert.toInt(deliveryAdd.getGoodLogId()));
                message.setSuccess(true);
                message.setMessage(ResponseData.DEFAULT_SUCCESS_MESSAGE);
                message.setCode("200");
            } else {
                message.setMessage("无数据");
                message.setSuccess(false);
                message.setCode("-1");
            }
        } catch (Exception e) {
            message.setMessage("无数据");
            message.setSuccess(false);
            message.setCode("-1");
            e.printStackTrace();
        }
        return message;
    }

    @Override
    public BusinessMessage selcetInGoldemDeatail(PlatformParam params) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = params.getPageSize();
            Integer pageNum = params.getPageNo();
            if (null == pageNum || Integer.valueOf(pageNum) <= 1) {
                pageNum = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            PlatformEntity platformEntity = new PlatformEntity();
            BeanUtil.copyProperties(params, platformEntity);
            PageHelper.startPage(pageNum, pageSize);
            List<Map<String, Object>> resultList = platformDao.selcetInGoldemDeatail(platformEntity);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("sumTotal", platformDao.selcetInGoldemDeatailTotal(platformEntity));
            if (resultList.size() >= 0) {
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
                resultMap.put("pageInfo", pageInfo);
                message.setData(resultMap);
                message.setSuccess(true);
                message.setMessage(ResponseData.DEFAULT_SUCCESS_MESSAGE);
                message.setCode("200");
            } else {
                message.setMessage("无数据");
                message.setSuccess(false);
                message.setCode("-1");
            }
        } catch (Exception e) {
            message.setMessage("无数据");
            message.setSuccess(false);
            message.setCode("-1");
            e.printStackTrace();
        }
        return message;

    }

    @Override
    public BusinessMessage selcetOutGoldemDeatail(ReflectRecordParam reflectRecordParam) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = reflectRecordParam.getPageSize();
            Integer pageNo = reflectRecordParam.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            ReflectRecord reflectRecord = new ReflectRecord();
            BeanUtil.copyProperties(reflectRecordParam, reflectRecord);
            if (null != reflectRecordParam.getBeginTime() && null != reflectRecordParam.getEndTime()) {
                Map<String, String> map = new HashMap<>(16);
                map = DateUtils.converTime(reflectRecordParam.getBeginTime(), reflectRecordParam.getEndTime());
                reflectRecord.setBeginTime(map.get("begin"));
                reflectRecord.setEndTime(map.get("end"));
            }
            if (null != reflectRecordParam.getDkBegin() && null != reflectRecordParam.getDkEnd()) {
                Map<String, String> map = new HashMap<>(16);
                map = DateUtils.conversionTime(reflectRecordParam.getDkBegin(), reflectRecordParam.getDkEnd());
                reflectRecord.setDkBegin(map.get("begin"));
                reflectRecord.setDkEnd(map.get("end"));
            }

            PageHelper.startPage(pageNo, pageSize);
            List<Map<String, Object>> resultList = platformDao.selcetOutGoldemDeatail(reflectRecord);
            Map<String, Object> resultMap = new HashMap<>();
            ReflectSummary reflectSummary = platformDao.reflectCount(reflectRecord);
            if (reflectSummary == null) {
                reflectSummary = new ReflectSummary();
            }
            resultMap.put("sumSXF", reflectSummary.getSumSXF());
            resultMap.put("sumDrawMoney", reflectSummary.getSumDrawMoney());
            resultMap.put("sumTotalAmount", reflectSummary.getSumTotalAmount());
            resultMap.put("sumTXMoney", reflectSummary.getSumTXMoney());
            if (resultList.size() >= 0) {
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
                resultMap.put("pageInfo", pageInfo);
                message.setData(resultMap);
                message.setSuccess(true);
                message.setMessage(ResponseData.DEFAULT_SUCCESS_MESSAGE);
                message.setCode("200");
            } else {
                message.setMessage("无数据");
                message.setSuccess(false);
                message.setCode("-1");
            }
        } catch (Exception e) {
            message.setMessage("无数据");
            message.setSuccess(false);
            message.setCode("-1");
            e.printStackTrace();
        }
        return message;
    }


    @Override
    public BusinessMessage selectPlatformDeliveryDetail(Map<String, Object> params) {
        BusinessMessage message = new BusinessMessage();
        try {
            String serialNum = null;
            if (params.get("serialNum") instanceof String) {
                serialNum = (String) params.get("serialNum");
            }
            if (params.get("serialNum") instanceof Integer) {
                serialNum = String.valueOf((Integer) params.get("serialNum"));
            }
            String logisticsNum = null;
            if (params.get("logisticsNum") instanceof String) {
                logisticsNum = (String) params.get("logisticsNum");
            }
            if (params.get("logisticsNum") instanceof Integer) {
                logisticsNum = String.valueOf((Integer) params.get("logisticsNum"));
            }

            Integer status = null;
            if (params.get("status") instanceof Integer) {
                status = (Integer) params.get("status");
            }
            if (params.get("status") instanceof String) {
                if (StringUtils.isNotBlank((String) params.get("status"))) {
                    status = Integer.valueOf((String) params.get("status"));
                }
            }
            Integer pageSize = null;
            if (params.get("pageSize") instanceof Integer) {
                pageSize = (Integer) params.get("pageSize");
            }
            if (params.get("pageSize") instanceof String) {
                if (StringUtils.isNotBlank((String) params.get("pageSize"))) {
                    pageSize = Integer.valueOf((String) params.get("pageSize"));
                }
            }
            Integer pageNum = null;
            if (params.get("pageNo") instanceof Integer) {
                pageNum = (Integer) params.get("pageNo");
            }
            if (params.get("pageNum") instanceof String) {
                if (StringUtils.isNotBlank((String) params.get("pageNum"))) {
                    pageNum = Integer.valueOf((String) params.get("pageNum"));
                }
            }

            if (null == pageNum || Integer.valueOf(pageNum) <= 1) {
                pageNum = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            PageHelper.startPage(pageNum, pageSize);
            List<Map<String, Object>> resultList = platformDao.selectPlatformDeliveryDetail(serialNum, logisticsNum, status);
            if (resultList.size() >= 0) {
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
                message.setData(pageInfo);
                message.setSuccess(true);
                message.setMessage(ResponseData.DEFAULT_SUCCESS_MESSAGE);
                message.setCode("200");
            } else {
                message.setSuccess(false);
                message.setMessage("无数据");
                message.setCode("-1");
            }
        } catch (Exception e) {
            message.setSuccess(false);
            message.setMessage("无数据");
            message.setCode("-1");
            e.printStackTrace();
        }
        return message;
    }

    @Override
    public BusinessMessage selectRemitDetail(ReflectRecordParam reflectRecordParam) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = reflectRecordParam.getPageSize();
            Integer pageNo = reflectRecordParam.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            ReflectRecord reflectRecord = new ReflectRecord();
            BeanUtil.copyProperties(reflectRecordParam, reflectRecord);
            if (null != reflectRecordParam.getBeginTime() && null != reflectRecordParam.getEndTime()) {
                Map<String, String> map = new HashMap<>(16);
                map = DateUtils.converTime(reflectRecordParam.getBeginTime(), reflectRecordParam.getEndTime());
                reflectRecord.setBeginTime(map.get("begin"));
                reflectRecord.setEndTime(map.get("end"));
            }
            if (null != reflectRecordParam.getDkBegin() && null != reflectRecordParam.getDkEnd()) {
                Map<String, String> map = new HashMap<>(16);
                map = DateUtils.conversionTime(reflectRecordParam.getDkBegin(), reflectRecordParam.getDkEnd());
                reflectRecord.setDkBegin(map.get("begin"));
                reflectRecord.setDkEnd(map.get("end"));
            }
            PageHelper.startPage(pageNo, pageSize);
            List<Map<String, Object>> resultList = platformDao.selectRemitDetail(reflectRecord);
            if (resultList == null || resultList.size() < 0) {
                message.setSuccess(false);
                message.setMessage("无数据");
                message.setCode("-1");
                return message;
            }
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
            Map<Object, Object> resultMap = new HashMap<>();
            ReflectSummary reflectSummary = platformDao.selectRemitDetailSum(reflectRecord);
            if (reflectSummary == null) {
                reflectSummary = new ReflectSummary();
            }
            resultMap.put("pageInfo", pageInfo);
            resultMap.put("sumMoney", reflectSummary.getSumMoney());
            resultMap.put("sumSXF", reflectSummary.getSumSXF());
            resultMap.put("sumTXMoney", reflectSummary.getSumTXMoney());
            message.setData(resultMap);
            message.setSuccess(true);
            message.setMessage(ResponseData.DEFAULT_SUCCESS_MESSAGE);
            message.setCode("200");
            return message;
        } catch (Exception e) {
            message.setSuccess(false);
            message.setMessage("无数据");
            message.setCode("-1");
            e.printStackTrace();
        }
        return message;
    }

    @Override
    @Transactional
    public BusinessMessage updateRemitStatus(Map<String, Object> params) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer orderId = (Integer) params.get("orderId");
            if (params.get("orderId") instanceof Integer) {
                orderId = (Integer) params.get("orderId");
            }
            if (params.get("orderId") instanceof String) {
                if (StringUtils.isBlank((String) params.get("orderId"))) {
                    message.setMessage("订单ID不能为空");
                    message.setSuccess(false);
                    message.setCode("-1");
                    return message;
                } else {
                    orderId = Integer.valueOf((String) params.get("orderId"));
                }
            }
            Integer loginUserId = null;
            if (params.get("loginUserId") instanceof Integer) {
                loginUserId = (Integer) params.get("loginUserId");
            }
            if (params.get("loginUserId") instanceof String) {
                if (StringUtils.isBlank((String) params.get("loginUserId"))) {
                    message.setMessage("操作人的ID不能为空");
                    message.setSuccess(false);
                    message.setCode("-1");
                    return message;
                } else {
                    loginUserId = Integer.valueOf((String) params.get("loginUserId"));
                }
            }
            if (null == loginUserId) {
                message.setMessage("操作人的ID不能为空");
                message.setSuccess(false);
                message.setCode("-1");
                return message;
            }

            String operationName = (String) params.get("operationName");

            if (StringUtils.isEmpty(operationName)){
                message.setMessage("操作人名称不能为空");
                message.setSuccess(false);
                message.setCode("-1");
                return message;
            }

            PvOrder order = pvOrderMapper.selectById(orderId);

            if (null != order) {
                order.setPaymentState(1);
                order.setPayTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                order.setUserId(loginUserId);
                order.setRemark("操作人：" + loginUserId);
                order.setOperationName(operationName);
                pvOrderMapper.updateById(order);
                message.setSuccess(true);
                message.setMessage(ResponseData.DEFAULT_SUCCESS_MESSAGE);
                message.setCode("200");
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                message.setSuccess(false);
                message.setMessage("无数据");
                message.setCode("-1");
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            message.setSuccess(false);
            message.setMessage("无数据");
            message.setCode("-1");
            e.printStackTrace();
        }
        return message;
    }


    @Override
    @Transactional
    public BusinessMessage updateBatchRemitStatus(Map<String, Object> params) {
        BusinessMessage message = new BusinessMessage();
        try {
            List<Integer> orderIds = (List<Integer>) params.get("orderIds");
            if (null == orderIds && orderIds.size() <= 0) {
                message.setMessage("ID不能为空");
                message.setSuccess(false);
                message.setCode("-1");
                return message;
            }
            Integer loginUserId = GetJavaTypeConvert.getInteger(params.get("loginUserId"));
            if (null == loginUserId) {
                message.setMessage("操作人的ID不能为空");
                message.setSuccess(false);
                message.setCode("-1");
                return message;
            }
            String operationName = (String) params.get("operationName");
            if (StringUtils.isEmpty(operationName)) {
                message.setMessage("操作人名称不能为空");
                message.setSuccess(false);
                message.setCode("-1");
                return message;
            }
            for (Integer orderId : orderIds) {
                PvOrder order = pvOrderMapper.selectById(orderId);
                order.setPaymentState(1);
                order.setPayTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                order.setUserId(loginUserId);
                order.setOperationName(operationName);
                order.setRemark("操作人：" + loginUserId);
                pvOrderMapper.updateById(order);
            }
            message.setSuccess(true);
            message.setMessage("成功处理了：" + orderIds.size() + "条");
            message.setCode("200");
            return message;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            message.setSuccess(false);
            message.setMessage("无数据");
            message.setCode("-1");
            e.printStackTrace();
        }
        return message;
    }


    @Override
    @Transactional
    public BusinessMessage updateJKStatus(Map<String, Object> params) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer deliveryId = GetJavaTypeConvert.getInteger(params.get("deliveryId"));
            Integer operatorId = GetJavaTypeConvert.getInteger(params.get("operatorId"));

            if (null == deliveryId) {
                message.setSuccess(false);
                message.setCode("-1");
                message.setMessage("deliveryId不能为空");
                return message;
            }
            if (null == operatorId) {
                message.setSuccess(false);
                message.setCode("-1");
                message.setMessage("操作人ID不能为空");
                return message;
            }
            PvDeliveryAdd pvDeliveryAdd = pvDeliveryAddMapper.selectById(deliveryId);
            if (null == pvDeliveryAdd) {
                message.setSuccess(false);
                message.setCode("-1");
                message.setMessage("操作订单不存在");
                return message;
            }

            if (!pvDeliveryAdd.getLogisticsStatus().equals("3")) {
                message.setSuccess(false);
                message.setCode("-1");
                message.setMessage("操作订单还没有确认收货");
                return message;
            }

            pvDeliveryAdd.setJkStatus("1");
            pvDeliveryAdd.setJkOperator(String.valueOf(operatorId));
            pvDeliveryAdd.setUpdateTime(new Date());
            int i = pvDeliveryAddMapper.updateById(pvDeliveryAdd);
            if (i == 1) {
                message.setSuccess(true);
                message.setCode("200");
                message.setMessage("操作成功");
                return message;
            }
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            message.setSuccess(false);
            message.setCode("-1");
            message.setMessage("操作失败");
            return message;

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            message.setSuccess(false);
            message.setMessage("无数据");
            message.setCode("-1");
            e.printStackTrace();
        }
        return message;
    }

    private boolean getPvShopByPhone(String phone) {
        boolean flag = false;
        LambdaQueryWrapper<PvShop> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PvShop::getPhone, phone);
        PvShop pvShop = pvShopMapper.selectOne(wrapper);
        if (pvShop != null) {
            if (StringUtils.isNotEmpty(pvShop.getPhone())) {
                flag = true;
            }
        }
        return flag;
    }

    @Override
    public BusinessMessage selectNotoginsengDetail(TradeParam tradeParam) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = tradeParam.getPageSize();
            Integer pageNo = tradeParam.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            TradeRequest tradeRequest = new TradeRequest();
            BeanUtil.copyProperties(tradeParam, tradeRequest);
            if (null != tradeParam.getBeginTime() && null != tradeParam.getEndTime()) {
                Map<String, String> map = new HashMap<>(16);
                map = DateUtils.conversionTime(tradeParam.getBeginTime(), tradeParam.getEndTime());
                tradeRequest.setBeginTime(map.get("begin"));
                tradeRequest.setEndTime(map.get("end"));
            }
            PageHelper.startPage(pageNo, pageSize);
            List<Map<String, Object>> resultList = platformDao.selecTnotoginsengDetail(tradeRequest);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
            Map<String, Object> resultMap = new HashMap<>();
            TradeSummary tradeSummary = platformDao.TradeSumy(tradeRequest);
            if (tradeSummary == null) {
                tradeSummary = new TradeSummary();
            }
            resultMap.put("sumYl", tradeSummary.getSumYl());
            resultMap.put("sumDJ", tradeSummary.getSumDJ());
            resultMap.put("sumSellOutTotal", tradeSummary.getSumSellOutTotal());
            resultMap.put("sumFRGWQ", tradeSummary.getSumFRGWQ());
            resultMap.put("sumFRZE", tradeSummary.getSumFRZE());
            resultMap.put("sumSXFZE", tradeSummary.getSumSXFZE());
            resultMap.put("sumZE", tradeSummary.getSumZE());
            resultMap.put("pageInfo", pageInfo);
            message.setData(resultMap);
            message.setSuccess(true);
            message.setMessage(Status.success);
            message.setCode(Status.successCode);
        } catch (Exception e) {
            message.setSuccess(false);
            message.setMessage(Status.fail);
            message.setCode(Status.failCode);
            e.printStackTrace();
        }
        return message;
    }

    @Override
    public BusinessMessage selectReleasedDetails(Map<String, Object> params) {
        BusinessMessage message = new BusinessMessage();
        try {
//            Long beginTime = (Long) params.get("beginTime");
//            Long endTime = (Long) params.get("endTime");
//            String accounts = (String) params.get("accounts");
            Integer pageSize = (Integer) params.get("pageSize");
            Integer pageNum = (Integer) params.get("pageNo");

            String accounts = null;
            if (params.get("accounts") instanceof String) {
                if (StringUtils.isNotBlank((String) params.get("accounts"))) {
                    accounts = (String) params.get("accounts");
                }
            }
            if (params.get("accounts") instanceof Integer) {
                accounts = String.valueOf((Integer) params.get("accounts"));
            }

            String productId = null;
            if (params.get("productId") instanceof String) {
                if (StringUtils.isNotBlank((String) params.get("productId"))) {
                    productId = (String) params.get("productId");
                }
            }
            if (params.get("productId") instanceof Integer) {
                productId = String.valueOf((Integer) params.get("productId"));
            }
            String productName = null;
            if (params.get("productName") instanceof String) {
                if (StringUtils.isNotBlank((String) params.get("productName"))) {
                    productName = (String) params.get("productName");
                }
            }
            Integer shopId = Convert.toInt(params.get("shopId"));
            Long beginTime = null;//开始时间
            if (params.get("beginTime") instanceof Long) {
                beginTime = (Long) params.get("beginTime");
            }
            if (params.get("beginTime") instanceof String) {
                if (StringUtils.isBlank((String) params.get("beginTime"))) {
                    beginTime = null;
                } else {
                    beginTime = Long.parseLong((String) params.get("beginTime"));
                }

            }
            Long endTime = null;//结束时间
            if (params.get("endTime") instanceof Long) {
                endTime = (Long) params.get("endTime");
            }
            if (params.get("endTime") instanceof String) {
                if (StringUtils.isBlank((String) params.get("endTime"))) {
                    endTime = null;
                } else {
                    endTime = Long.parseLong((String) params.get("endTime"));
                }
            }

            if (null == pageNum || Integer.valueOf(pageNum) <= 1) {
                pageNum = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            Map<String, String> map = new HashMap<>();
            String begin = null;
            String end = null;
            if (null != beginTime && null != endTime) {
                map = DateUtils.conversionTime(beginTime, endTime);
                begin = map.get("begin");
                end = map.get("end");
            }
            PageHelper.startPage(pageNum, pageSize); // 设置分页参数
            List<Map<String, Object>> resultList = platformDao.selectReleasedDetails(accounts, begin, end, productId, productName, shopId);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
            Map<Object, Object> resultMap = new HashMap<>();
            resultMap.put("sumReleaseNum", platformDao.selectReleasedDetailsTotal(accounts, begin, end, productId, productName, shopId));
            resultMap.put("pageInfo", pageInfo);
            message.setData(resultMap);
            message.setSuccess(true);
            message.setMessage(Status.success);
            message.setCode(Status.successCode);

        } catch (Exception e) {
            message.setMessage(Status.fail);
            message.setSuccess(false);
            message.setCode(Status.failCode);
            e.printStackTrace();
        }
        return message;
    }

    /**
     * 获取商铺列表
     *
     * @param pvShopReqParam
     * @return
     */
    @Override
    public BusinessMessage list(PvShopReqParam pvShopReqParam) {
        BusinessMessage<Object> message = new BusinessMessage<>();
        LambdaQueryWrapper<PvShop> queryWrapper = new LambdaQueryWrapper<>();
        if (com.cn.xiaonuo.common.utils.StringUtils.isNotEmpty(pvShopReqParam.getShopName())) {
            queryWrapper.eq(PvShop::getShopName, pvShopReqParam.getShopName());
        }

        queryWrapper.eq(PvShop::getStatus, 1);
        List<PvShop> list = pvShopMapper.selectList(queryWrapper);
        message.setSuccess(true);
        message.setCode("200");
        message.setData(list);
        return message;
    }

    /**
     * 奖励记录
     *
     * @param platformParam
     * @return
     */
    @Override
    public BusinessMessage rewardPage(PlatformParam platformParam) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = platformParam.getPageSize();
            Integer pageNo = platformParam.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            PlatformEntity platformEntity = new PlatformEntity();
            BeanUtil.copyProperties(platformParam, platformEntity);
        /*    if (null != platformParam.getBeginTime() && null != platformParam.getEndTime()) {
                Map<String, String> map = new HashMap<>(16);
                map=DateUtils.conversionTime(platformParam.getBeginTime() , platformParam.getEndTime());
                platformEntity.setBegin(map.get("begin"));
                platformEntity.setEnd(map.get("end"));
            }*/
            PageHelper.startPage(pageNo, pageSize);
            // List<Map<String, Object>> resultList = platformDao.rewardPage(platformEntity);//老的奖励接口
            List<Map<String, Object>> resultList = pvPossessionGoodsRewardMapper.goodsRewardPage(platformEntity);//调用新奖励接口
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
            Map<String, Object> resultMap = new HashMap<>();
            //Double rewardSummary=platformDao.rewardSumy(platformEntity);
            Double rewardSummary = pvPossessionGoodsRewardMapper.goodsRewardSumy(platformEntity);
            if (rewardSummary == null) {
                rewardSummary = 0d;
            }
            resultMap.put("sumZE", rewardSummary);
            resultMap.put("pageInfo", pageInfo);
            message.setData(resultMap);
            message.setSuccess(true);
            message.setMessage(Status.success);
            message.setCode(Status.successCode);
        } catch (Exception e) {
            message.setSuccess(false);
            message.setMessage(Status.fail);
            message.setCode(Status.failCode);
            e.printStackTrace();
        }
        return message;
    }

    /**
     * 剩余记录
     *
     * @param platformParam
     * @return
     */
    @Override
    public BusinessMessage surplusPage(PlatformParam platformParam) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = platformParam.getPageSize();
            Integer pageNo = platformParam.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            PlatformEntity platformEntity = new PlatformEntity();
            BeanUtil.copyProperties(platformParam, platformEntity);
            PageHelper.startPage(pageNo, pageSize);
            List<Map<String, Object>> resultList = platformDao.surplusPage(platformEntity);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
            Map<String, Object> resultMap = new HashMap<>();
            Double surplusSummary = platformDao.surplusSum(platformEntity);
            if (surplusSummary == null) {
                surplusSummary = 0d;
            }
            resultMap.put("sumZE", surplusSummary);
            resultMap.put("pageInfo", pageInfo);
            message.setData(resultMap);
            message.setSuccess(true);
            message.setMessage(Status.success);
            message.setCode(Status.successCode);
        } catch (Exception e) {
            message.setSuccess(false);
            message.setMessage(Status.fail);
            message.setCode(Status.failCode);
            e.printStackTrace();
        }
        return message;
    }

    /**
     * 奖品合计
     *
     * @param platformParamam
     * @return
     */
    @Override
    public BusinessMessage prizeTotalPage(PlatformParam platformParamam) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = platformParamam.getPageSize();
            Integer pageNo = platformParamam.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            PlatformEntity platformEntity = new PlatformEntity();
            BeanUtil.copyProperties(platformParamam, platformEntity);
            PageHelper.startPage(pageNo, pageSize);
            // List<Map<String, Object>> resultList = platformDao.prizeTotalPage(platformEntity);//老奖励接口
            List<Map<String, Object>> resultList = pvPossessionGoodsRewardMapper.prizeTotalPage(platformEntity);//新奖励接口
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
            Map<String, Object> resultMap = new HashMap<>();
            // Double rewardSummary=platformDao.prizeSum(platformEntity);//老奖励接口
            Double rewardSummary = pvPossessionGoodsRewardMapper.prizeSum(platformEntity);//新奖励接口
            if (rewardSummary == null) {
                rewardSummary = 0d;
            }
            resultMap.put("sumZE", rewardSummary);
            resultMap.put("pageInfo", pageInfo);
            message.setData(resultMap);
            message.setSuccess(true);
            message.setMessage(Status.success);
            message.setCode(Status.successCode);
        } catch (Exception e) {
            message.setSuccess(false);
            message.setMessage(Status.fail);
            message.setCode(Status.failCode);
            e.printStackTrace();
        }
        return message;
    }

    /**
     * 赠品记录
     *
     * @param platformParamam
     * @return
     */
    @Override
    public BusinessMessage giftPage(PlatformParam platformParamam) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = platformParamam.getPageSize();
            Integer pageNo = platformParamam.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            PlatformEntity platformEntity = new PlatformEntity();
            BeanUtil.copyProperties(platformParamam, platformEntity);
            PageHelper.startPage(pageNo, pageSize);
            List<Map<String, Object>> resultList = platformDao.giftPage(platformEntity);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
            Map<String, Object> resultMap = new HashMap<>();
            Double rewardSummary = platformDao.giftSum(platformEntity);
            if (rewardSummary == null) {
                rewardSummary = 0d;
            }
            resultMap.put("sumZE", rewardSummary);
            resultMap.put("pageInfo", pageInfo);
            message.setData(resultMap);
            message.setSuccess(true);
            message.setMessage(Status.success);
            message.setCode(Status.successCode);
        } catch (Exception e) {
            message.setSuccess(false);
            message.setMessage(Status.fail);
            message.setCode(Status.failCode);
            e.printStackTrace();
        }
        return message;
    }

    @Override
    public BusinessMessage selectDeliveryAdd(PvShopParam pvShopParam) {
        BusinessMessage message = new BusinessMessage();
        if (pvShopParam.getDeliveryId() != null) {
            PvDeliveryAdd pvDeliveryAdd = pvDeliveryAddMapper.selectById(pvShopParam.getDeliveryId());
            if (pvDeliveryAdd != null) {
                message.setSuccess(true);
                message.setMessage(Status.success);
                message.setCode(Status.successCode);
                message.setData(pvDeliveryAdd);
                return message;
            }
        }
        return null;
    }

    @Override
    public BusinessMessage selectGeneralOrderList(PvOrderRequest pvOrderRequest) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = pvOrderRequest.getPageSize();
            Integer pageNo = pvOrderRequest.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }

            PageHelper.startPage(pageNo, pageSize);
            List<Map<String, Object>> resultList = platformDao.selectGeneralOrderList(pvOrderRequest);
            if (resultList.size() >= 0) {
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(resultList);
                message.setData(pageInfo);
                message.setSuccess(true);
                message.setMessage("请求成功");
                message.setCode("200");
            } else {
                message.setMessage("无数据");
                message.setSuccess(false);
                message.setCode("-1");
            }
        } catch (Exception e) {
            message.setMessage("请求失败");
            message.setSuccess(false);
            message.setCode("-1");
            e.printStackTrace();
        }
        return message;

    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public BusinessMessage generateRefundOrder(PvOrderRefund pvOrderRefund) {
        BusinessMessage message = new BusinessMessage();
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        if (pvOrderRefund.getOperateId() == null) {
            message.setMessage("审核人ID不能为空");
            message.setSuccess(false);
            message.setCode("-1");
            return message;
        }
        //查询用户是否为有效用户
        SysUserHpcEntity sysUserHpcEntity = sysUserHpcMapper.selectById(pvOrderRefund.getOperateId());
        PvOrderRefundLog pvOrderRefundLog = new PvOrderRefundLog();
        PvOrderRefund pvOrderRefundResponse = new PvOrderRefund();
        if (sysUserHpcEntity != null) {
            pvOrderRefundResponse.setOperateId(sysUserHpcEntity.getUserId());
            pvOrderRefundResponse.setOperateName(sysUserHpcEntity.getUsername());
            pvOrderRefundResponse.setOperateStatus(1);
            pvOrderRefundLog.setOperateId(sysUserHpcEntity.getUserId());
            pvOrderRefundLog.setOperateName(sysUserHpcEntity.getUsername());
            pvOrderRefundLog.setOperateType(1);

        }
        //用当前时间加上六位数字生成一个退款订单编号
        String orderNum = OrderNumGeneration.generateOrderId();
        pvOrderRefundResponse.setRefundNum(orderNum);
        if (pvOrderRefund.getOrderId() == null) {
            message.setMessage("订单id不能为空");
            message.setSuccess(false);
            message.setCode("-1");
            return message;
        }
        PvOrder pvOrder = pvOrderMapper.selectById(pvOrderRefund.getOrderId());
        if (pvOrder != null) {
            pvOrderRefundResponse.setOrderId(pvOrder.getId());
            pvOrderRefundResponse.setSerialNumber(pvOrder.getSerialNumber());
            pvOrderRefundResponse.setProductId(pvOrder.getProductId());
            pvOrderRefundResponse.setProductName(pvOrder.getProductName());
            pvOrderRefundResponse.setProductNum(pvOrder.getDelistingNumber());
            pvOrderRefundResponse.setTotalAmount(pvOrder.getTotalAmount());
            pvOrderRefundResponse.setActualAmount(pvOrder.getTotalAmount());
            pvOrderRefundResponse.setPaymentChannel(pvOrder.getPaymentChannel());
            pvOrderRefundLog.setOrderId(pvOrder.getId());
            pvOrderRefundLog.setSerialNumber(pvOrder.getSerialNumber());
            pvOrderRefundLog.setRefundAmount(pvOrder.getTotalAmount());
        }
        PvLoginUser pvLoginUser = pvLoginUserMapper.selectById(pvOrder.getDelistingUserId());
        if (pvLoginUser == null) {
            message.setMessage("摘单用户不存在");
            message.setSuccess(false);
            message.setCode("-1");
            return message;
        }
        pvOrderRefundResponse.setUserId(pvLoginUser.getId());
        pvOrderRefundResponse.setUserName(pvLoginUser.getRealName());
        PvDeliveryAdd pvDeliveryAdd = pvDeliveryAddMapper.selectOne(new QueryWrapper<>(new PvDeliveryAdd() {{
            setGoodLogId(String.valueOf(pvOrder.getId()));
        }}));
        String logisticsStatus = pvDeliveryAdd.getLogisticsStatus();
        if (pvDeliveryAdd != null) {
            if (!(logisticsStatus.equals("1") || logisticsStatus.equals("2"))) {
                message.setMessage("请勿重复提交，可刷新页面后重试！");
                message.setSuccess(false);
                message.setCode("-1");
                return message;
            }
            pvOrderRefundResponse.setUserAddress(pvDeliveryAdd.getProvince() + "/" + pvDeliveryAdd.getCity() + "/" + pvDeliveryAdd.getCounty());
            pvOrderRefundResponse.setPhone(pvDeliveryAdd.getPhone());
            pvOrderRefundResponse.setDeliveryId(pvDeliveryAdd.getId());
            PvDeliveryAdd pvDeliveryAdd1 = new PvDeliveryAdd();
            pvDeliveryAdd1.setLogisticsStatus("5");
            pvDeliveryAdd1.setId(pvDeliveryAdd.getId());
            pvDeliveryAdd1.setCheckState(2);
            pvOrderRefundLog.setLogisticsStatus(Integer.valueOf(pvDeliveryAdd.getLogisticsStatus()));
            pvOrderRefundLog.setPreOperateStatus(2);
            pvOrderRefundLog.setOperateStatus(2);
            pvDeliveryAddMapper.updateById(pvDeliveryAdd1);
            pvOrder.setLogisticsStatus(5);
            pvOrder.setUpdatedAt(date);
            pvOrderMapper.updateById(pvOrder);
        }
        pvOrderRefundResponse.setCreateTime(format);
        pvOrderRefundResponse.setOrderRefundState(1);
        pvOrderRefundResponse.setCheckState(2);
        pvOrderRefundResponse.setOperateMode(2);
        pvOrderRefundResponse.setRemark(pvOrderRefund.getRemark());
        PvProduct pvProduct = pvProductMapper.selectById(pvOrder.getProductId());
        PvShop pvShop = pvShopMapper.selectById(pvProduct.getShopId());
        pvOrderRefundResponse.setShopId(pvShop.getId());
        pvOrderRefundResponse.setShopName(pvShop.getShopName());
        pvOrderRefundMapper.insert(pvOrderRefundResponse);
        pvOrderRefundLog.setValidState(1);
        pvOrderRefundLog.setRemark(pvOrderRefund.getRemark());
        pvOrderRefundLog.setCreateTime(format);
        pvOrderRefundLog.setRefundId(pvOrderRefundResponse.getId());
        pvOrderRefundLogMapper.insert(pvOrderRefundLog);
        message.setMessage(Status.success);
        message.setSuccess(true);
        message.setCode(Status.successCode);
        return message;
    }

    @Override
    public BusinessMessage selectFinanceRefund(PvOrderRequest pvOrderRequest) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = pvOrderRequest.getPageSize();
            Integer pageNo = pvOrderRequest.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            PageHelper.startPage(pageNo, pageSize);
           /* List<Map<String, Object>>  pvOrderRefunds = pvOrderRefundMapper.selectFinanceRefund(pvOrderRequest);
            if (pvOrderRefunds.size() >= 0) {
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(pvOrderRefunds);
                message.setData(pageInfo);
                message.setSuccess(true);
                message.setMessage("请求成功");
                message.setCode("200");
            } else {
                message.setMessage("无数据");
                message.setSuccess(false);
                message.setCode("-1");
            }*/
            LambdaQueryWrapper<PvOrderRefund> wrapper = new LambdaQueryWrapper<>();
            if (com.cn.xiaonuo.common.utils.StringUtils.isNotEmpty(pvOrderRequest.getRefundNum())) {
                wrapper.eq(PvOrderRefund::getRefundNum, pvOrderRequest.getRefundNum());
            }
            if (com.cn.xiaonuo.common.utils.StringUtils.isNotEmpty(pvOrderRequest.getSerialNumber())) {
                wrapper.eq(PvOrderRefund::getSerialNumber, pvOrderRequest.getSerialNumber());
            }
            if (pvOrderRequest.getPhone() != null && pvOrderRequest.getPhone() != "") {
                wrapper.eq(PvOrderRefund::getPhone, pvOrderRequest.getPhone());
            }
            if (com.cn.xiaonuo.common.utils.StringUtils.isNotEmpty(pvOrderRequest.getProductName())) {
                wrapper.like(PvOrderRefund::getProductName, pvOrderRequest.getProductName());
            }
            if (com.cn.xiaonuo.common.utils.StringUtils.isNotEmpty(pvOrderRequest.getShopName())) {
                wrapper.eq(PvOrderRefund::getShopName, pvOrderRequest.getShopName());
            }
            if (pvOrderRequest.getShopId() != null && pvOrderRequest.getShopId() != 0) {
                wrapper.eq(PvOrderRefund::getShopId, pvOrderRequest.getShopId());
            }
            if (pvOrderRequest.getPaymentChannel() != null && pvOrderRequest.getPaymentChannel() != 0) {
                wrapper.eq(PvOrderRefund::getPaymentChannel, pvOrderRequest.getPaymentChannel());
            }
            if (pvOrderRequest.getOperateMode() != null && pvOrderRequest.getOperateMode() != 0) {
                wrapper.eq(PvOrderRefund::getOperateMode, pvOrderRequest.getOperateMode());
            }
            if (pvOrderRequest.getCheckState() != null && pvOrderRequest.getCheckState() != 0) {
                wrapper.eq(PvOrderRefund::getCheckState, pvOrderRequest.getCheckState());
            }
            if (pvOrderRequest.getUserName() != null && pvOrderRequest.getUserName() != "") {
                wrapper.eq(PvOrderRefund::getUserName, pvOrderRequest.getUserName());
            }
            if (null != pvOrderRequest.getCreateBeginTime() && "" != pvOrderRequest.getCreateEndTime()) {
                wrapper.between(PvOrderRefund::getCreateTime, pvOrderRequest.getCreateBeginTime(), pvOrderRequest.getCreateEndTime());
            }
            if (null != pvOrderRequest.getCheckBeginTime() && "" != pvOrderRequest.getCheckEndTime()) {
                wrapper.between(PvOrderRefund::getCheckTime, pvOrderRequest.getCheckBeginTime(), pvOrderRequest.getCheckEndTime());
            }
            if (null != pvOrderRequest.getPaymentEndTime() && "" != pvOrderRequest.getPaymentBeginTime()) {
                wrapper.between(PvOrderRefund::getPaymentTime, pvOrderRequest.getPaymentBeginTime(), pvOrderRequest.getPaymentEndTime());
            }
            if (ObjectUtils.isNotEmpty(pvOrderRequest.getMerchantOrderNo())) {
                wrapper.eq(PvOrderRefund::getMerchantOrderNo, pvOrderRequest.getMerchantOrderNo());
            }
            wrapper.orderByDesc(PvOrderRefund::getCreateTime);
            List<PvOrderRefund> pvOrderRefunds = pvOrderRefundMapper.selectList(wrapper);
            PageInfo<PvOrderRefund> pageInfo = new PageInfo<>(pvOrderRefunds);
            message.setData(pageInfo);
            message.setSuccess(true);
            message.setMessage(Status.success);
            message.setCode(Status.successCode);
        } catch (Exception e) {
            message.setCode("-1");
            message.setMessage("操作失败");
            message.setSuccess(false);
            e.printStackTrace();
        }
        return message;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public BusinessMessage refundOrderReview(PvOrderRequest pvOrderRequest) {
        BusinessMessage message = new BusinessMessage();
        try {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(date);
            if (pvOrderRequest.getRefundId() == null) {
                message.setCode(Status.failCode);
                message.setMessage("退款账号id不能为空");
                message.setSuccess(false);
                return message;
            }

            LambdaQueryWrapper<PvOrderRefund> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(PvOrderRefund::getId, pvOrderRequest.getRefundId());
            PvOrderRefund selectPvOrderRefund = pvOrderRefundMapper.selectOne(queryWrapper);
            if (selectPvOrderRefund == null) {
                message.setCode(Status.failCode);
                message.setMessage("订单信息有误！");
                message.setSuccess(false);
                return message;
            }
            PvOrderRefund pvOrderRefund = new PvOrderRefund();
            PvDeliveryAdd pvDeliveryAdd = new PvDeliveryAdd();
            PvOrderRefundLog pvOrderRefundLog = new PvOrderRefundLog();
            pvOrderRefund.setId(pvOrderRequest.getRefundId());
            pvOrderRefundLog.setOrderId(selectPvOrderRefund.getOrderId());
            pvOrderRefundLog.setSerialNumber(selectPvOrderRefund.getSerialNumber());
            pvOrderRefundLog.setRefundId(selectPvOrderRefund.getId());
            pvOrderRefundLog.setRefundAmount(selectPvOrderRefund.getActualAmount());
            if (pvOrderRequest.getCheckState() == null) {
                message.setCode(Status.failCode);
                message.setMessage("审核状态不能为空");
                message.setSuccess(false);
                return message;
            }
            LambdaQueryWrapper<PvDeliveryAdd> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PvDeliveryAdd::getGoodLogId, selectPvOrderRefund.getOrderId());
            PvDeliveryAdd pvDeliveryAdd1 = pvDeliveryAddMapper.selectOne(wrapper);
            PvOrder pvOrder = pvOrderMapper.selectById(selectPvOrderRefund.getOrderId());
            if (pvDeliveryAdd1 != null) {
                if (pvDeliveryAdd1.getCheckState() != 1) {
                    message.setCode(Status.failCode);
                    message.setMessage("请勿重复提交，可刷新页面后重试！");
                    message.setSuccess(false);
                    return message;
                }
                if (pvOrderRequest.getCheckState() == 2) {
                    pvOrderRefund.setCheckState(2);
                    pvOrderRefundLog.setOperateStatus(2);
                    pvOrderRefundLog.setPreOperateStatus(2);
                    pvOrderRefundLog.setLogisticsStatus(5);
                    pvDeliveryAdd.setId(pvDeliveryAdd1.getId());
                    pvDeliveryAdd.setLogisticsStatus("5");
                    pvDeliveryAdd.setCheckState(2);
                    pvOrder.setLogisticsStatus(5);
                }
                if (pvOrderRequest.getCheckState() == 4) {
                    if (pvOrderRequest.getRefuseReasonId() != 0 && pvOrderRequest.getRefuseReasonId() != null) {
                        LambdaQueryWrapper<NSysConfig> nSysConfigWrapper = new LambdaQueryWrapper<>();
                        nSysConfigWrapper.eq(NSysConfig::getId, pvOrderRequest.getRefuseReasonId());
                        NSysConfig nSysConfig = nSysConfigMapper.selectOne(nSysConfigWrapper);
                        pvOrderRefund.setCheckState(4);
                        pvOrderRefund.setRefuseReasonId(pvOrderRequest.getRefuseReasonId());
                        pvOrderRefund.setRefuseReason(nSysConfig.getValue());
                        pvOrderRefundLog.setOperateStatus(4);
                        pvOrderRefundLog.setPreOperateStatus(4);
                        pvOrderRefundLog.setLogisticsStatus(1);
                        pvDeliveryAdd.setId(pvDeliveryAdd1.getId());
                        pvDeliveryAdd.setLogisticsStatus("1");
                        pvDeliveryAdd.setCheckState(4);
                        pvOrder.setLogisticsStatus(1);
                    } else {
                        message.setCode(Status.failCode);
                        message.setMessage("驳回原因不能为空!");
                        message.setSuccess(false);
                        return message;
                    }
                }
            }
            if (selectPvOrderRefund != null) {
                pvOrderRefund.setOperateMode(1);
                pvOrderRefund.setCheckTime(format);
            }
            if (pvOrderRequest.getOperateId() == null) {
                message.setCode(Status.failCode);
                message.setMessage("操作人id不能为空");
                message.setSuccess(false);
                return message;
            }
            SysUserHpcEntity sysUserHpcEntity = sysUserHpcMapper.selectById(pvOrderRequest.getOperateId());
            if (sysUserHpcEntity.getUserId() == null) {
                message.setCode(Status.failCode);
                message.setMessage("该用户不存在");
                message.setSuccess(false);
                return message;
            }
            pvOrderRefund.setOperateId(sysUserHpcEntity.getUserId());
            pvOrderRefund.setOperateName(sysUserHpcEntity.getUsername());
            pvOrderRefund.setOperateStatus(1);
            pvOrderRefundLog.setOperateId(sysUserHpcEntity.getUserId());
            pvOrderRefundLog.setOperateName(sysUserHpcEntity.getUsername());
            pvOrderRefundLog.setOperateType(1);
            pvOrderRefundLog.setValidState(1);
            pvOrderRefundMapper.updateById(pvOrderRefund);
            pvDeliveryAddMapper.updateById(pvDeliveryAdd);
            pvOrderRefundLog.setCreateTime(format);
            pvOrderRefundLog.setCheckTime(format);
            pvOrderRefundLog.setRemark(selectPvOrderRefund.getRemark());
            pvOrderRefundLogMapper.insert(pvOrderRefundLog);
            pvOrder.setUpdatedAt(new Date());
            pvOrderMapper.updateById(pvOrder);
            message.setCode(Status.successCode);
            message.setMessage(Status.success);
            message.setSuccess(true);
        } catch (Exception e) {
            message.setCode(Status.failCode);
            message.setMessage(Status.fail);
            message.setSuccess(false);
            e.printStackTrace();
        }

        return message;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public BusinessMessage cancelRefund(PvOrderRequest pvOrderRequest) {
        BusinessMessage message = new BusinessMessage();
        try {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(date);
            if (pvOrderRequest.getRefundId() == null) {
                message.setCode(Status.failCode);
                message.setMessage("退款订单id不能为空");
                message.setSuccess(false);
                return message;
            }
            PvOrderRefund pvOrderRefund = pvOrderRefundMapper.selectById(pvOrderRequest.getRefundId());
            if (pvOrderRefund == null) {
                message.setCode(Status.failCode);
                message.setMessage("该退款订单信息不存在");
                message.setSuccess(false);
                return message;
            }
            PvOrderRefundLog pvOrderRefundLog = new PvOrderRefundLog();
            PvOrderRefund pvOrderRefund1 = new PvOrderRefund();
            pvOrderRefundLog.setOrderId(pvOrderRefund.getOrderId());
            pvOrderRefundLog.setSerialNumber(pvOrderRefund.getSerialNumber());
            pvOrderRefundLog.setRefundId(pvOrderRefund.getId());
            pvOrderRefundLog.setCreateTime(format);
            pvOrderRefundLog.setRefundAmount(pvOrderRefund.getActualAmount());
            pvOrderRefund1.setCheckState(5);
            pvOrderRefundLog.setOperateStatus(5);
            pvOrderRefundLog.setPreOperateStatus(5);
            SysUserHpcEntity sysUserHpcEntity = sysUserHpcMapper.selectById(pvOrderRefund.getOperateId());
            if (sysUserHpcEntity.getUserId() == null) {
                message.setCode(Status.failCode);
                message.setMessage("该用户不存在");
                message.setSuccess(false);
                return message;
            }
            pvOrderRefund1.setOperateId(sysUserHpcEntity.getUserId());
            pvOrderRefund1.setOperateName(sysUserHpcEntity.getUsername());
            pvOrderRefund1.setCheckTime(format);
            pvOrderRefund1.setId(pvOrderRequest.getRefundId());
            pvOrderRefundLog.setOperateId(sysUserHpcEntity.getUserId());
            pvOrderRefundLog.setOperateName(sysUserHpcEntity.getUsername());
            pvOrderRefundLog.setOperateType(1);
            pvOrderRefundLog.setValidState(1);
            pvOrderRefundMapper.updateById(pvOrderRefund1);
            PvDeliveryAdd pvDeliveryAdd = new PvDeliveryAdd();
            LambdaQueryWrapper<PvDeliveryAdd> LambdaQueryWrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper.eq(PvDeliveryAdd::getGoodLogId, pvOrderRefund.getOrderId());
            PvDeliveryAdd selectPvDeliveryAdd = pvDeliveryAddMapper.selectOne(LambdaQueryWrapper);
            if (selectPvDeliveryAdd == null) {
                message.setCode(Status.failCode);
                message.setMessage("订单信息有误！");
                message.setSuccess(false);
                return message;
            }
            pvDeliveryAdd.setId(selectPvDeliveryAdd.getId());
            pvDeliveryAdd.setLogisticsStatus("1");
            pvDeliveryAdd.setCheckState(5);
            pvDeliveryAddMapper.updateById(pvDeliveryAdd);
            pvOrderRefundLog.setLogisticsStatus(1);
            pvOrderRefundLog.setRemark(pvOrderRefund.getRemark());
            pvOrderRefundLogMapper.insert(pvOrderRefundLog);
            PvOrder pvOrder = pvOrderMapper.selectById(selectPvDeliveryAdd.getGoodLogId());
            pvOrder.setLogisticsStatus(1);
            pvOrder.setUpdatedAt(date);
            pvOrderMapper.updateById(pvOrder);
            message.setCode(Status.successCode);
            message.setMessage(Status.success);
            message.setSuccess(true);
        } catch (Exception e) {
            message.setCode(Status.failCode);
            message.setMessage(Status.fail);
            message.setSuccess(false);
            e.printStackTrace();
        }
        return message;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public BusinessMessage confirmRefund(PvOrderRequest pvOrderRequest) {

        BusinessMessage message = new BusinessMessage();
        try {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(date);
            if (pvOrderRequest.getRefundId() == null) {
                message.setCode(Status.failCode);
                message.setMessage("退款订单id不能为空");
                message.setSuccess(false);
                return message;
            }
            PvOrderRefund pvOrderRefund = pvOrderRefundMapper.selectById(pvOrderRequest.getRefundId());
            if (pvOrderRefund == null) {
                message.setCode(Status.failCode);
                message.setMessage("该退款订单信息不存在");
                message.setSuccess(false);
                return message;
            }
            if (pvOrderRefund.getOperateId() == null) {
                message.setCode(Status.failCode);
                message.setMessage("操作人id不能为空");
                message.setSuccess(false);
                return message;
            }
            PvOrderRefundLog pvOrderRefundLog = new PvOrderRefundLog();
            PvOrderRefund pvOrderRefund1 = new PvOrderRefund();
            pvOrderRefundLog.setOperateStatus(3);
            pvOrderRefundLog.setPreOperateStatus(3);
            pvOrderRefundLog.setOrderId(pvOrderRefund.getOrderId());
            pvOrderRefundLog.setSerialNumber(pvOrderRefund.getSerialNumber());
            pvOrderRefundLog.setRefundId(pvOrderRefund.getId());
            pvOrderRefundLog.setRefundAmount(pvOrderRefund.getActualAmount());
            SysUserHpcEntity sysUserHpcEntity = sysUserHpcMapper.selectById(pvOrderRefund.getOperateId());
            if (sysUserHpcEntity.getUserId() == null) {
                message.setCode(Status.failCode);
                message.setMessage("该用户不存在");
                message.setSuccess(false);
                return message;
            }
            pvOrderRefund1.setOperateId(sysUserHpcEntity.getUserId());
            pvOrderRefund1.setOperateName(sysUserHpcEntity.getUsername());
            pvOrderRefund1.setPaymentId(sysUserHpcEntity.getUserId());
            pvOrderRefund1.setPaymentName(sysUserHpcEntity.getUsername());
            pvOrderRefund1.setCheckTime(format);
            pvOrderRefund1.setPaymentTime(format);
            pvOrderRefundLog.setOperateId(sysUserHpcEntity.getUserId());
            pvOrderRefundLog.setOperateName(sysUserHpcEntity.getUsername());
            pvOrderRefundLog.setOperateType(1);
            pvOrderRefundLog.setValidState(1);
            pvOrderRefundLog.setRemark(pvOrderRefund.getRemark());
            pvOrderRefundLog.setCreateTime(format);
            pvOrderRefund1.setId(pvOrderRequest.getRefundId());
            pvOrderRefund1.setPaymentStatus(1);

            PvDeliveryAdd pvDeliveryAdd = new PvDeliveryAdd();
            LambdaQueryWrapper<PvDeliveryAdd> LambdaQueryWrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper.eq(PvDeliveryAdd::getGoodLogId, pvOrderRefund.getOrderId());
            PvDeliveryAdd selectPvDeliveryAdd = pvDeliveryAddMapper.selectOne(LambdaQueryWrapper);
            if (selectPvDeliveryAdd == null) {
                message.setCode(Status.failCode);
                message.setMessage("订单信息有误！");
                message.setSuccess(false);
                return message;
            }
            PvOrder pvOrder = pvOrderMapper.selectById(selectPvDeliveryAdd.getGoodLogId());
           /* if (pvOrder.getPaymentChannel().equals(9) || pvOrder.getPaymentChannel().equals(10) || pvOrder.getPaymentChannel().equals(10)) {
                BusinessMessage tradequery = this.tradequery(pvOrder.getSerialNumber(), pvOrderRefund.getRefundNum(), pvOrderRefund.getActualAmount().movePointRight(2).longValue(), pvOrderRefund.getReason());
                Object data = tradequery.getData();
                JSONObject responseJson= JSON.parseObject((String) data);
                if ("BBS00000".equals(responseJson.get("code").toString())){
                    pvOrderRefund1.setCheckState(3);
                    pvOrderRefundMapper.updateById(pvOrderRefund1);
                    LambdaQueryWrapper<ShopSettlement> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(ShopSettlement::getSerialNumber,pvOrder.getSerialNumber());
                    wrapper.eq(ShopSettlement::getSettlementStatus,1);
                    ShopSettlement settlement = shopSettlementMapper.selectOne(wrapper);
                    if (ObjectUtils.isNotEmpty(settlement)){
                        settlement.setSettlementStatus(5);
                        settlement.setLogisticsStatus(7);
                        shopSettlementMapper.updateById(settlement);
                    }
                }else {
                    pvOrderRefund1.setCheckState(6);
                    pvOrderRefundMapper.updateById(pvOrderRefund1);
                    message.setCode(Status.failCode);
                    message.setMessage("退款失败！");
                    message.setSuccess(false);
                    return message;
                }
            }else {*/
            pvOrderRefund1.setCheckState(3);
            pvOrderRefundMapper.updateById(pvOrderRefund1);
//            }
            pvDeliveryAdd.setId(selectPvDeliveryAdd.getId());
            pvDeliveryAdd.setLogisticsStatus("6");
            pvDeliveryAdd.setCheckState(3);
            pvOrderRefundLog.setLogisticsStatus(6);
            pvDeliveryAddMapper.updateById(pvDeliveryAdd);
            pvOrderRefundLogMapper.insert(pvOrderRefundLog);

            //20为余额支付，余额支付退款需退还余额
            if (pvOrder.getPaymentChannel() == 20) {
                PvWalletLog pvWalletLog = new PvWalletLog();
                LambdaQueryWrapper<PvWallet> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(PvWallet::getUserId, pvOrder.getDelistingUserId());
                PvWallet pvWallet = pvWalletMapper.selectOne(wrapper);
                pvWalletLog.setBeforeChangeBalance(pvWallet.getAvailableBalance());

                //可用余额等于该笔订单总金额加上原先可用余额
                BigDecimal temporary = pvOrder.getTotalAmount().add(pvWallet.getAvailableBalance());
                pvWallet.setAvailableBalance(temporary);
                pvWalletMapper.updateById(pvWallet);
                pvWalletLog.setUserId(pvWallet.getUserId());
                pvWalletLog.setOderId(pvOrder.getId());
                pvWalletLog.setAfterChangeBalance(temporary);
                pvWalletLog.setCreateTime(format);
                pvWalletLog.setUpdateTime(new Date());
                pvWalletLog.setTypes(10);
                pvWalletLog.setRemarks("退款了：" + pvOrderRefund.getProductNum() + "件");
                pvWalletLog.setOperation(Convert.toInt(sysUserHpcEntity.getUserId()));
                pvWalletLogMapper.insert(pvWalletLog);
            }
            pvOrder.setLogisticsStatus(6);
            pvOrder.setUpdatedAt(date);
            pvOrderMapper.updateById(pvOrder);
            //String outTradeNo,String refundOrderNo,Long refundAmount,String refundReason
            message.setCode(Status.successCode);
            message.setMessage(Status.success);
            message.setSuccess(true);
        } catch (Exception e) {
            message.setCode(Status.failCode);
            message.setMessage(e.getMessage());
            message.setSuccess(false);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return message;
    }

    @Override
    public BusinessMessage pickUpOrder(PvOrderRequest pvOrderRequest) {

        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = pvOrderRequest.getPageSize();
            Integer pageNo = pvOrderRequest.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            PageHelper.startPage(pageNo, pageSize);
            List<Map<String, Object>> selectPvOrder = pvOrderMapper.selectPickUpOrder(pvOrderRequest);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(selectPvOrder);
            message.setCode("200");
            message.setData(pageInfo);
            message.setMessage("操作成功");
            message.setSuccess(true);
        } catch (Exception e) {
            message.setCode("-1");
            message.setMessage("操作失败");
            message.setSuccess(false);
            e.printStackTrace();
        }
        return message;
    }

    @Override
    public BusinessMessage cancelPicking(PvOrderRequest pvOrderRequest) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = pvOrderRequest.getPageSize();
            Integer pageNo = pvOrderRequest.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            PageHelper.startPage(pageNo, pageSize);
            LambdaQueryWrapper<PvOrderDelivery> wrapper = new LambdaQueryWrapper<>();
            if (pvOrderRequest.getSerialNumber() != null && pvOrderRequest.getSerialNumber() != "") {
                wrapper.eq(PvOrderDelivery::getSerialNumber, pvOrderRequest.getSerialNumber());
            }
            if (pvOrderRequest.getCreateBeginTime() != null && pvOrderRequest.getCreateEndTime() != "") {
                wrapper.between(PvOrderDelivery::getCreateTime, pvOrderRequest.getCreateBeginTime(), pvOrderRequest.getCreateEndTime());
            }
            if (pvOrderRequest.getCheckBeginTime() != null && pvOrderRequest.getCheckEndTime() != "") {
                wrapper.between(PvOrderDelivery::getCheckTime, pvOrderRequest.getCheckBeginTime(), pvOrderRequest.getCheckEndTime());
            }
            if (pvOrderRequest.getUserName() != null && pvOrderRequest.getUserName() != "") {
                wrapper.eq(PvOrderDelivery::getUserName, pvOrderRequest.getUserName());
            }
            if (pvOrderRequest.getPhone() != null && pvOrderRequest.getPhone() != "") {
                wrapper.eq(PvOrderDelivery::getPhone, pvOrderRequest.getPhone());
            }
            if (pvOrderRequest.getProductName() != null && pvOrderRequest.getProductName() != "") {
                wrapper.eq(PvOrderDelivery::getProductName, pvOrderRequest.getProductName());
            }
            if (pvOrderRequest.getShopName() != null && pvOrderRequest.getShopName() != "") {
                wrapper.eq(PvOrderDelivery::getShopName, pvOrderRequest.getShopName());
            }
            if (pvOrderRequest.getShopId() != null && pvOrderRequest.getShopId() != 0) {
                wrapper.eq(PvOrderDelivery::getShopId, pvOrderRequest.getShopId());
            }
            if (pvOrderRequest.getDeliveryMode() != null && pvOrderRequest.getDeliveryMode() != 0) {
                wrapper.eq(PvOrderDelivery::getDeliveryMode, pvOrderRequest.getDeliveryMode());
            }
            if (pvOrderRequest.getCheckState() != null && pvOrderRequest.getCheckState() != 0) {
                wrapper.eq(PvOrderDelivery::getCheckState, pvOrderRequest.getCheckState());
            }
            if (pvOrderRequest.getOperateMode() != null && pvOrderRequest.getOperateMode() != 0) {
                wrapper.eq(PvOrderDelivery::getOperateMode, pvOrderRequest.getOperateMode());
            }
            wrapper.orderByDesc(PvOrderDelivery::getCreateTime);
            List<PvOrderDelivery> pvOrderDeliveries = pvOrderDeliveryMapper.selectList(wrapper);
            PageInfo<PvOrderDelivery> pageInfo = new PageInfo<>(pvOrderDeliveries);
            message.setCode(Status.successCode);
            message.setMessage(Status.success);
            message.setData(pageInfo);
            message.setSuccess(true);
        } catch (Exception e) {
            message.setCode(Status.failCode);
            message.setMessage(Status.fail);
            message.setSuccess(false);
            e.printStackTrace();
        }
        return message;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public BusinessMessage cancelPickingReview(PvOrderDeliverysParam pvOrderDeliverysParam) throws Exception {

        BusinessMessage message = new BusinessMessage();
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        if (pvOrderDeliverysParam.getOperateId() == null) {
            message.setSuccess(false);
            message.setMessage("操作人id不能为空！");
            message.setCode(Status.failCode);
            return message;
        }
        //审核操作人为财务系统当前登录用户
        SysUserHpcEntity sysUserHpcEntity = sysUserHpcMapper.selectById(pvOrderDeliverysParam.getOperateId());
        if (sysUserHpcEntity == null) {
            message.setSuccess(false);
            message.setMessage("审核操作人信息有误！");
            message.setCode(Status.failCode);
            return message;
        }
        PvLoginUser pvLoginUser = pvLoginUserMapper.selectById(pvOrderDeliverysParam.getUserId());
        if (null == pvLoginUser) {
            message.setSuccess(false);
            message.setMessage("用户不存在！");
            return message;
        }
        if (pvOrderDeliverysParam.getDeliveryId() == null) {
            message.setCode(Status.failCode);
            message.setSuccess(false);
            message.setMessage("提货订单信息不能为空！");
            return message;
        }
        PvOrderDeliveryLog pvOrderDeliveryLog = new PvOrderDeliveryLog();
        PvOrderDelivery pvOrderDelivery = pvOrderDeliveryMapper.selectById(pvOrderDeliverysParam.getDeliveryId());//查询提货订单信息
        if (pvOrderDelivery == null) {
            message.setCode(Status.failCode);
            message.setSuccess(false);
            message.setMessage("提货订单信息有误！");
            return message;
        }
        Integer checkState = pvOrderDelivery.getCheckState();
        if (checkState != 1) {
            message.setCode(Status.failCode);
            message.setSuccess(false);
            message.setMessage("请勿重复提交，可刷新页面后重试！");
            return message;
        }
        if (pvOrderDeliverysParam.getCheckState() == 2) {
            //还原提货数量
            //new 一个对象用于参数传参
            PvOrderDelivery pvOrderDelivery1 = new PvOrderDelivery();
            pvOrderDelivery1.setUserId(pvOrderDeliverysParam.getUserId());
            pvOrderDelivery1.setProductId(pvOrderDeliverysParam.getProductId());
            pvOrderDelivery1.setOrderId(Convert.toInt(pvOrderDeliverysParam.getGoodLogId()));
            //返还数量执行代码
            this.restorePickingQuantity(pvOrderDelivery1);
            PvDeliveryAdd pvDeliveryAdd = pvDeliveryAddMapper.selectOne(new QueryWrapper<>(new PvDeliveryAdd() {{
                setGoodLogId(pvOrderDeliverysParam.getGoodLogId());
            }}));
            pvDeliveryAdd.setLogisticsStatus(Integer.toString(7));
            pvDeliveryAddMapper.updateById(pvDeliveryAdd);
            //设置流水表数据
            pvOrderDelivery.setOperateId(sysUserHpcEntity.getUserId());
            pvOrderDelivery.setOperateName(sysUserHpcEntity.getUsername());
            pvOrderDelivery.setOrderState(1);
            pvOrderDelivery.setOperateStatus(1);
            pvOrderDelivery.setCheckState(2);
            pvOrderDelivery.setCheckTime(format);
            pvOrderDeliveryLog.setOrderId(pvOrderDelivery.getOrderId());
            pvOrderDeliveryLog.setSerialNumber(pvOrderDelivery.getSerialNumber());
            pvOrderDeliveryLog.setDeliveryId(pvOrderDelivery.getId());
            pvOrderDeliveryLog.setCreateTime(format);
            pvOrderDeliveryLog.setOperateType(1);
            pvOrderDeliveryLog.setOperateStatus(2);
            pvOrderDeliveryLog.setPreOperateStatus(pvOrderDelivery.getCheckState());
            pvOrderDeliveryLog.setLogisticsStatus(4);
            pvOrderDeliveryLog.setOperateId(sysUserHpcEntity.getUserId());
            pvOrderDeliveryLog.setOperateName(sysUserHpcEntity.getUsername());
            pvOrderDeliveryLog.setDeliveryAmount(pvOrderDelivery.getActualAmount());
            pvOrderDeliveryMapper.updateById(pvOrderDelivery);
            pvOrderDeliveryLogMapper.insert(pvOrderDeliveryLog);
            storageRecordService.deleteStorageRecord(Convert.toInt(pvOrderDeliverysParam.getGoodLogId()));
        }
        if (pvOrderDeliverysParam.getCheckState() == 3) {
            pvOrderDelivery.setCheckState(3);
            pvOrderDelivery.setCheckTime(format);
            pvOrderDelivery.setOperateId(sysUserHpcEntity.getUserId());
            pvOrderDelivery.setOperateName(sysUserHpcEntity.getUsername());
            pvOrderDelivery.setOrderState(1);
            pvOrderDelivery.setOperateStatus(1);
            if (pvOrderDeliverysParam.getRefuseReasonId() == 0 || pvOrderDeliverysParam.getRefuseReasonId() == null) {
                message.setCode(Status.failCode);
                message.setSuccess(false);
                message.setMessage("驳回原因不能为空！");
                return message;
            }
            pvOrderDelivery.setRefuseReasonId(pvOrderDeliverysParam.getRefuseReasonId());
            NSysConfig nSysConfig = nSysConfigMapper.selectById(pvOrderDeliverysParam.getRefuseReasonId());
            pvOrderDelivery.setRefuseReason(nSysConfig.getValue());
            pvOrderDeliveryMapper.updateById(pvOrderDelivery);
            pvOrderDeliveryLog.setCreateTime(format);
            pvOrderDeliveryLog.setDeliveryAmount(pvOrderDelivery.getActualAmount());
            BeanUtil.copyProperties(pvOrderDelivery, pvOrderDeliveryLog);
            pvOrderDeliveryLogMapper.insert(pvOrderDeliveryLog);
            PvDeliveryAdd pvDeliveryAdd = pvDeliveryAddMapper.selectOne(new QueryWrapper<>(new PvDeliveryAdd() {{
                setGoodLogId(pvOrderDeliverysParam.getGoodLogId());
            }}));
            pvDeliveryAdd.setLogisticsStatus(Integer.toString(1));
            pvDeliveryAddMapper.updateById(pvDeliveryAdd);
        }
        message.setCode(Status.successCode);
        message.setMessage(Status.success);
        message.setSuccess(true);
        return message;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public BusinessMessage deliveryGenerateRefundOrder(PvOrderDelivery pvOrderDelivery) throws Exception {
        BusinessMessage message = new BusinessMessage();
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        if (pvOrderDelivery.getOperateId() == null) {
            message.setMessage("审核人ID不能为空");
            message.setSuccess(false);
            message.setCode("-1");
            return message;
        }
        if (pvOrderDelivery.getUserId() == null && pvOrderDelivery.getProductId() == null) {
            message.setMessage("退货人id和商品id不能为空！");
            message.setSuccess(false);
            message.setCode("-1");
            return message;
        }
        //查询用户是否为有效用户，此用户为当前登录财务系统的用户
        SysUserHpcEntity sysUserHpcEntity = sysUserHpcMapper.selectById(pvOrderDelivery.getOperateId());
        PvOrderDeliveryLog pvOrderDeliverLog = new PvOrderDeliveryLog();
        PvOrderDelivery pvOrderDeliveryResponse = new PvOrderDelivery();
        if (sysUserHpcEntity != null) {
            pvOrderDeliveryResponse.setOperateId(sysUserHpcEntity.getUserId());
            pvOrderDeliveryResponse.setOperateName(sysUserHpcEntity.getUsername());
            pvOrderDeliveryResponse.setOperateStatus(1);
            pvOrderDeliverLog.setOperateId(sysUserHpcEntity.getUserId());
            pvOrderDeliverLog.setOperateName(sysUserHpcEntity.getUsername());
            pvOrderDeliverLog.setOperateType(1);

        }
        String orderNum = OrderNumGeneration.generateOrderId();
        pvOrderDeliveryResponse.setDeliveryNum(orderNum);
        if (pvOrderDelivery.getSerialNumber() == null) {
            message.setMessage("订单编号不能为空");
            message.setSuccess(false);
            message.setCode("-1");
            return message;
        }
        LambdaQueryWrapper<PvOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PvOrder::getSerialNumber, pvOrderDelivery.getSerialNumber());
        PvOrder pvOrder = pvOrderMapper.selectOne(wrapper);
        if (pvOrder != null) {
            pvOrder.setPaymentState(2);
            pvOrderMapper.updateById(pvOrder);
            pvOrderDeliveryResponse.setOrderId(pvOrder.getId());
            pvOrderDeliveryResponse.setSerialNumber(pvOrder.getSerialNumber());
            pvOrderDeliveryResponse.setProductId(pvOrder.getProductId());
            pvOrderDeliveryResponse.setProductName(pvOrder.getProductName());
            pvOrderDeliveryResponse.setProductNum(pvOrder.getDelistingNumber());
            pvOrderDeliveryResponse.setTotalAmount(pvOrder.getTotalAmount());
            pvOrderDeliveryResponse.setActualAmount(pvOrder.getTotalAmount());
            pvOrderDeliveryResponse.setDeliveryMode(pvOrder.getPaymentChannel());
            pvOrderDeliverLog.setOrderId(pvOrder.getId());
            pvOrderDeliverLog.setSerialNumber(pvOrder.getSerialNumber());
            pvOrderDeliverLog.setDeliveryAmount(pvOrder.getTotalAmount());
            if (pvOrder.getPickUserId() != null) {
                PvLoginUser pvLoginUser = pvLoginUserMapper.selectById(pvOrder.getPickUserId());
                pvOrderDeliveryResponse.setUserId(pvLoginUser.getId());
                pvOrderDeliveryResponse.setUserName(pvLoginUser.getRealName());
            }
        }

        PvDeliveryAdd pvDeliveryAdd = pvDeliveryAddMapper.selectOne(new QueryWrapper<>(new PvDeliveryAdd() {{
            setGoodLogId(String.valueOf(pvOrder.getId()));
        }}));
        String logisticsStatus = pvDeliveryAdd.getLogisticsStatus();
        if (pvDeliveryAdd != null) {
            if (!(logisticsStatus.equals("1") || logisticsStatus.equals("2"))) {
                message.setMessage("请勿重复提交，可刷新页面后重试！");
                message.setSuccess(false);
                message.setCode(Status.failCode);
                return message;
            }
            pvOrderDeliveryResponse.setUserAddress(pvDeliveryAdd.getProvince() + "/" + pvDeliveryAdd.getCity() + "/" + pvDeliveryAdd.getCounty());
            pvOrderDeliveryResponse.setPhone(pvDeliveryAdd.getPhone());
            pvOrderDeliveryResponse.setDeliveryId(pvDeliveryAdd.getId());
            PvDeliveryAdd pvDeliveryAdd1 = new PvDeliveryAdd();
            pvDeliveryAdd1.setLogisticsStatus("7");
            pvDeliveryAdd1.setId(pvDeliveryAdd.getId());
            pvOrderDeliverLog.setLogisticsStatus(Integer.valueOf(pvDeliveryAdd.getLogisticsStatus()));
            pvOrderDeliverLog.setPreOperateStatus(pvDeliveryAdd.getCheckState());
            pvOrderDeliverLog.setOperateStatus(pvDeliveryAdd.getCheckState());
            pvDeliveryAddMapper.updateById(pvDeliveryAdd1);
        }
        pvOrderDeliveryResponse.setCreateTime(format);
        pvOrderDeliveryResponse.setOrderState(1);
        pvOrderDeliveryResponse.setCheckState(2);
        pvOrderDeliveryResponse.setOperateMode(2);
        pvOrderDeliveryResponse.setShopId(pvOrder.getShopId());
        PvShop pvShop = pvShopMapper.selectById(pvOrder.getShopId());
        if (pvShop == null) {
            message.setMessage("所属商家信息不存在！");
            message.setSuccess(false);
            message.setCode(Status.failCode);
            return message;
        }
        pvOrderDeliveryResponse.setShopName(pvShop.getShopName());
        pvOrderDeliveryResponse.setRemark(pvOrderDelivery.getRemark());
        pvOrderDeliveryResponse.setDeliveryMode(pvDeliveryAdd.getOrderStatus());
        pvOrderDeliveryMapper.insert(pvOrderDeliveryResponse);
        pvOrderDeliverLog.setValidState(1);
        pvOrderDeliverLog.setRemark(pvOrderDelivery.getRemark());
        pvOrderDeliverLog.setCreateTime(format);
        pvOrderDeliverLog.setDeliveryId(pvOrderDelivery.getId());
        pvOrderDeliveryLogMapper.insert(pvOrderDeliverLog);
        //还原提货数量
        this.restorePickingQuantity(pvOrderDelivery);
        storageRecordService.deleteStorageRecord(pvOrder.getId());
        message.setMessage(Status.success);
        message.setSuccess(true);
        message.setCode(Status.successCode);

        return message;
    }

    @Override
    public BusinessMessage idmRefundQuery(String outRefundOrderNo) {
        BusinessMessage message = new BusinessMessage<>();
        String url = LakalaPayUtil.IDM_REFUND_QUERY;
        try {
            JSONObject body = new JSONObject();
            body.put("version", "3.0");
            body.put("req_time", DateUtils.formatDateYyyyMMddHHmmss(new Date()));
            body.put("out_org_code", "OP00000003");
            JSONObject requestData = new JSONObject();
            requestData.put("merchant_no", LakalaPayUtil.MCH_ID);
            requestData.put("term_no", LakalaPayUtil.TERM_NO);
            //退款订单编号
            requestData.put("out_refund_order_no", outRefundOrderNo);
            body.put("req_data", requestData);
            String tmpeBody = body.toString() + "\n";
            System.out.println("tmpeBody:" + tmpeBody);
            log.info("退款查询请求开始");
            String authorization = LakalaPayCommon.getAuthorization(tmpeBody);
            HttpResponse response = LakalaPayCommon.post(LakalaPayUtil.LAKALA_URL + url, tmpeBody, authorization);
            if (response.getStatusLine().getStatusCode() != 200) {
                System.out.println("请求失败，statusCode  " + response.getStatusLine()
                        + IOUtils.toString(response.getEntity().getContent(), LakalaPayUtil.ENCODING));
                message.setSuccess(false);
                message.setMessage("请求失败，statusCode");
                message.setCode("-1");
                return message;
            }
            String appid = LakalaPayCommon.getHeadValue(response, "Lklapi-Appid");
            String lklapiSerial = LakalaPayCommon.getHeadValue(response, "Lklapi-Serial");
            String timestamp = LakalaPayCommon.getHeadValue(response, "Lklapi-Timestamp");
            String nonce = LakalaPayCommon.getHeadValue(response, "Lklapi-Nonce");
            String signature = LakalaPayCommon.getHeadValue(response, "Lklapi-Signature");
            String responseStr = IOUtils.toString(response.getEntity().getContent(), LakalaPayUtil.ENCODING);
            log.info("responseStr:{}", responseStr);
            String source = appid + "\n" + lklapiSerial + "\n" + timestamp + "\n" + nonce + "\n" + responseStr + "\n";
            X509Certificate lklCertificate = LakalaPayCommon.loadCertificate(new FileInputStream(new File(LakalaPayUtil.PUBULIC_KEY)));

            boolean verify = LakalaPayCommon.verify(lklCertificate, source.getBytes(LakalaPayUtil.ENCODING), signature);
            if (verify) {
                message.setData(responseStr);
                message.setMessage(Status.success);
                message.setSuccess(true);
                message.setCode("200");
                log.info("验签成功:");

            } else {
                message.setSuccess(false);
                message.setMessage("验签不通过、支付失败，重新支付");
                message.setCode("-1");
                log.info("验签失败:");
                return message;
            }
        } catch (Exception e) {
            message.setSuccess(false);
            message.setData(e.getMessage());
            message.setMessage("查询失败");
            message.setCode("-1");
            log.error("退款查询失败，原因：{}", e.getMessage());
        }
        return message;
    }

    /**
     * @描述 取消提货申请同意与关闭订单同意调用此方法还原数量
     * @参数 UserId 退货人id ，ProductId商品id
     * @返回值
     * @创建人 likui
     * @创建时间 2022/3/18
     */
    public void restorePickingQuantity(PvOrderDelivery pvOrderDelivery) throws Exception {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        PvOrderDeliverysParam pvOrderDeliverysParam = new PvOrderDeliverysParam();
        pvOrderDeliverysParam.setUserId(pvOrderDelivery.getUserId());
        pvOrderDeliverysParam.setProductId(pvOrderDelivery.getProductId());
        pvOrderDeliverysParam.setGoodLogId(Convert.toStr(pvOrderDelivery.getOrderId()));
        //根据用户id和商品id查询最近一条流水做参照进行
        List<Map<String, Object>> pvPossessionGoodsRewards = pvPossessionGoodsRewardMapper.cancelPicking(pvOrderDeliverysParam);
        PvPossessionGoods pvPossessionGood = new PvPossessionGoods();
        PvPossessionGoods pvPossessionGoods = pvPossessionGoodsMapper.selectOne(new QueryWrapper<>(new PvPossessionGoods() {{
            setUserId(pvOrderDelivery.getUserId());
            setProductId(pvOrderDelivery.getProductId());
        }}));
        Integer possessionGoodsRewardId = null;
        List<String> baseIdLogList1 = null;
        Integer userId = null;
        Integer productId = null;


        ArrayList<Integer> baseLogId = new ArrayList<>();
        BigDecimal beforFrozeNuumber = pvPossessionGoods.getPossessNumber();//之前的冻结数量
        BigDecimal afterFrozenNumber = pvPossessionGoods.getPossessNumber();//之前的冻结数量
        BigDecimal frozenNumber = new BigDecimal(0);//冻结变化数量
        BigDecimal beforeNumber = pvPossessionGoods.getCansellNumber();
        BigDecimal afterNumber = pvPossessionGoods.getCansellNumber();
        BigDecimal availableNumber = new BigDecimal(0);
        ArrayList<HashMap<Object, Object>> list = new ArrayList<>();
        for (Map map : pvPossessionGoodsRewards) {
            pvPossessionGood.setUpdatedAt(new Date());
            possessionGoodsRewardId = Convert.toInt(map.get("id"));
            String baseIdLogs = Convert.toStr(map.get("base_log_id"));
            if (StringUtils.isNotBlank(baseIdLogs)) {
                String[] str = baseIdLogs.split(",");
                baseIdLogList1 = Arrays.asList(str);
            }
            userId = Convert.toInt(map.get("user_id"));
            productId = Convert.toInt(map.get("product_id"));
            Map<String, String> dateMap = new HashMap<>(16);
            //如果释放订单表数量呗扣除了则需要还原base表数量
            if (baseIdLogList1 != null) {
                List<Map<String, Object>> pvReleaseBaseLogList = pvReleaseBaseLogMapper.queryBaseId(baseIdLogList1, userId, productId);
                if (pvReleaseBaseLogList != null) {
                    PvReleaseBase pvReleaseBase = new PvReleaseBase();
                    PvReleaseBaseLog pvReleaseBaseLog = new PvReleaseBaseLog();
                    for (Map map1 : pvReleaseBaseLogList) {
                        HashMap<Object, Object> baseMap = new HashMap<>();
                        BigDecimal bs_num = Convert.toBigDecimal(map1.get("bs_num"));//base变化数量
                        pvReleaseBaseLog.setAfterNum(Convert.toBigDecimal(map1.get("after_num")));
                        pvReleaseBaseLog.setReleaseId(Convert.toInt(map1.get("release_id")));
                        pvReleaseBaseLog.setBsNum(Convert.toBigDecimal(map1.get("bs_num")));
                        pvReleaseBaseLog.setCreateTime(format);
                        pvReleaseBaseLog.setUpdateTime(format);
                        pvReleaseBaseLog.setOperateStatus(2);
                        pvReleaseBaseLog.setBeforeNum(Convert.toBigDecimal(map1.get("purchase_num")));
                        Integer baseId = Convert.toInt(map1.get("release_id"));
                        PvReleaseBase pvReleaseBase1 = pvReleaseBaseMapper.selectById(baseId);
                        if (pvReleaseBase1.getSTime() != null && pvReleaseBase1.getCTime() != null) {
                            String cTime = simpleDateFormat.format(pvReleaseBase1.getNewCTime());
                            if (ObjectUtils.isEmpty(cTime)) {
                                cTime = pvReleaseBase1.getCTime();
                            }
                            String sTime = pvReleaseBase1.getSTime();
                            Date ctime1 = stringToYmd(cTime);
                            Date sTime1 = simpleDateFormat.parse(sTime);
                            int i = DateUtils.compare_date(sTime, format);
                            Long aLong = DateUtils.minusDay(sTime1, ctime1, true);
                            boolean flag = true;
                            if (i == -1 || i == 0) {
                                if (aLong >= 14) {
                                    baseMap.put("baseId", pvReleaseBase1.getId());
                                    baseMap.put("baseLogId", map1.get("id"));
                                    baseMap.put("bsNum", map1.get("bs_num"));
                                    list.add(baseMap);
                                    flag = false;
                                    afterNumber = afterNumber.add(bs_num);
                                    availableNumber = availableNumber.add(bs_num);
                                } else if (aLong >= 13 && pvReleaseBase1.getDType() == 5) {
                                    baseMap.put("baseId", pvReleaseBase1.getId());
                                    baseMap.put("baseLogId", map1.get("id"));
                                    baseMap.put("bsNum", map1.get("bs_num"));
                                    list.add(baseMap);
                                    flag = false;
                                    afterNumber = afterNumber.add(bs_num);
                                    availableNumber = availableNumber.add(bs_num);
                                }
                            }
                            if (flag) {
                                afterFrozenNumber = afterFrozenNumber.add(bs_num);
                                frozenNumber = frozenNumber.add(bs_num);
                            }

                        }
                        if (baseMap.isEmpty()) {
                            pvReleaseBaseLog.setAfterNum(pvReleaseBase1.getPurchaseNum().add(pvReleaseBaseLog.getBsNum()));
                            pvReleaseBaseLogMapper.insert(pvReleaseBaseLog);
                            baseLogId.add(pvReleaseBaseLog.getId());
                            pvReleaseBase.setId(baseId);//baseId
                            //可卖数余额等于当前可卖数余额加上扣减数量
                            pvReleaseBase.setPurchaseNum(pvReleaseBase1.getPurchaseNum().add(pvReleaseBaseLog.getBsNum()));
                            pvReleaseBaseMapper.updateById(pvReleaseBase);
                        }
                    }

                }
            }
            pvPossessionGood.setId(pvPossessionGoods.getId());
            if (list.size() > 0) {
                pvPossessionGood.setCansellNumber(afterNumber);
                pvPossessionGood.setPossessNumber(afterFrozenNumber);

            } else {
                //如果判空参数有一个为空则不能进行相加   购买提货
                if (Convert.toInt(map.get("frozen_number")) != null && Convert.toInt(map.get("frozen_number")) > 0 && pvPossessionGoods.getPossessNumber() != null) {
                    //用户拥有商品信息表拥有数量等于pv_possession_goods_reward 的frozen_number（冻结变化数量）加上剩余的拥有数量
                    pvPossessionGood.setPossessNumber(Convert.toBigDecimal(map.get("frozen_number")).add(pvPossessionGoods.getPossessNumber()));
                }
                //购买提货
                if (Convert.toInt(map.get("available_number")) != null && Convert.toInt(map.get("available_number")) > 0 && pvPossessionGoods.getCansellNumber() != null) {
                    //用户拥有商品信息表可买数量等于pv_possession_goods_reward 的frozen_number（冻结变化数量）加上剩余的可买数量
                    pvPossessionGood.setCansellNumber(Convert.toBigDecimal(map.get("available_number")).add(pvPossessionGoods.getCansellNumber()));
                }
            }
            //奖励提货
            if (Convert.toInt(map.get("change_reward")) != null && Convert.toInt(map.get("change_reward")) > 0) {
                pvPossessionGood.setRewardNum(Convert.toInt(Convert.toBigDecimal(map.get("change_reward")).add(Convert.toBigDecimal(pvPossessionGoods.getRewardNum()))));
            }

        }
        log.info("用户ID：" + pvOrderDeliverysParam.getUserId());
        log.info("商品ID：" + pvOrderDeliverysParam.getProductId());
        LambdaQueryWrapper<PvPossessionGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PvPossessionGoods::getProductId, pvOrderDeliverysParam.getProductId());
        queryWrapper.eq(PvPossessionGoods::getUserId, pvOrderDeliverysParam.getUserId());
        PvPossessionGoods pvPossessionGoods1 = pvPossessionGoodsMapper.selectOne(queryWrapper);
        pvPossessionGoodsMapper.updateById(pvPossessionGood);
        PvPossessionGoodsReward pvPossessionGoodsReward = new PvPossessionGoodsReward();
        PvPossessionGoodsReward pvPossessionGoodsReward1 = pvPossessionGoodsRewardMapper.selectById(possessionGoodsRewardId);
        //查询改用户下当前商品拥有数量
        BeanUtil.copyProperties(pvPossessionGoodsReward1, pvPossessionGoodsReward);
        String baseLogIdList = baseLogId.stream().map(String::valueOf).collect(Collectors.joining(","));
        pvPossessionGoodsReward.setBaseLogId(baseLogIdList);
        pvPossessionGoodsReward.setCreateTime(format);
        pvPossessionGoodsReward.setUpdatedAt(new Date());
        //奖励提货
        if (pvPossessionGoodsReward1.getChangeReward().compareTo(new BigDecimal(0)) > 0) {
            pvPossessionGoodsReward.setBeforeReward(Convert.toBigDecimal(pvPossessionGoods1.getRewardNum()));
            pvPossessionGoodsReward.setAfterReward(Convert.toBigDecimal(pvPossessionGoods1.getRewardNum()).add(pvPossessionGoodsReward1.getChangeReward()));
        }
        if (list.size() > 0) {

            pvPossessionGoodsReward.setBeforeNumber(beforeNumber);
            pvPossessionGoodsReward.setAfterNumber(afterNumber);
            pvPossessionGoodsReward.setBeforFrozenNumber(beforFrozeNuumber);
            pvPossessionGoodsReward.setAfterFrozenNumber(afterFrozenNumber);
            pvPossessionGoodsReward.setFrozenNumber(frozenNumber);
            pvPossessionGoodsReward.setAvailableNumber(availableNumber);

        } else {
            //如果冻结变化量和可卖变化量为空则为奖励数量提货
            if (pvPossessionGoodsReward1.getFrozenNumber() != null) {
                pvPossessionGoodsReward.setBeforFrozenNumber(pvPossessionGoods1.getPossessNumber());
                //冻结之后的数量等于原冻结之后的数量加上冻结变化数量
                pvPossessionGoodsReward.setAfterFrozenNumber(pvPossessionGoods1.getPossessNumber().add(pvPossessionGoodsReward1.getFrozenNumber()));
            } else {
                //冻结数量如果没有变化，那么将商品现有的用有量赋值到变化数量上
                pvPossessionGoodsReward.setBeforFrozenNumber(pvPossessionGoods1.getPossessNumber());
                pvPossessionGoodsReward.setAfterFrozenNumber(pvPossessionGoods1.getPossessNumber());
            }
            if (pvPossessionGoodsReward1.getAvailableNumber() != null) {
                pvPossessionGoodsReward.setBeforeNumber(pvPossessionGoods1.getCansellNumber());
                //之后可卖数量等于原之后可卖数量加上可卖变化数量
                pvPossessionGoodsReward.setAfterNumber(pvPossessionGoods1.getCansellNumber().add(pvPossessionGoodsReward1.getAvailableNumber()));

            } else {
                pvPossessionGoodsReward.setBeforeNumber(pvPossessionGoods1.getCansellNumber());
                pvPossessionGoodsReward.setAfterNumber(pvPossessionGoods1.getCansellNumber());
            }

        }
        pvPossessionGoodsReward.setState(4);
        pvPossessionGoodsRewardMapper.insert(pvPossessionGoodsReward);

    }

    /*
     * 将String时间类型换为时间Date
     */
    public Date stringToYmd(String s) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.parse(s);
    }


    public BusinessMessage tradequery(String outTradeNo, String refundOrderNo, Long refundAmount, String refundReason) {
        BusinessMessage message = new BusinessMessage<>();
        String url = LakalaPayUtil.IDMRE_FUND;
        try {
            JSONObject body = new JSONObject();
            body.put("version", "3.0");
            body.put("req_time", DateUtils.formatDateYyyyMMddHHmmss(new Date()));
            body.put("out_org_code", "OP00000003");
            JSONObject requestData = new JSONObject();
            requestData.put("merchant_no", LakalaPayUtil.MCH_ID);
            requestData.put("term_no", LakalaPayUtil.TERM_NO);
            //下单编号
            requestData.put("origin_out_trade_no", outTradeNo);
            //退款订单编号
            requestData.put("out_refund_order_no", refundOrderNo);
            //退款金额
            requestData.put("refund_amount", refundAmount);
            //备注
            requestData.put("refund_reason", refundReason);
            JSONObject locationInfo = new JSONObject();
            locationInfo.put("request_ip", "127.0.0.1");
            requestData.put("location_info", locationInfo);
            body.put("req_data", requestData);
            log.info("body:{}", body);
            String tmpeBody = body.toString() + "\n";
            System.out.println("tmpeBody:" + tmpeBody);
            log.info("退款请求开始");
            String authorization = LakalaPayCommon.getAuthorization(tmpeBody);
            HttpResponse response = LakalaPayCommon.post(LakalaPayUtil.LAKALA_URL + url, tmpeBody, authorization);
            if (response.getStatusLine().getStatusCode() != 200) {
                System.out.println("请求失败，statusCode  " + response.getStatusLine()
                        + IOUtils.toString(response.getEntity().getContent(), LakalaPayUtil.ENCODING));
                message.setSuccess(false);
                message.setMessage("请求失败，statusCode");
                message.setCode("-1");
                return message;
            }
            String appid = LakalaPayCommon.getHeadValue(response, "Lklapi-Appid");
            String lklapiSerial = LakalaPayCommon.getHeadValue(response, "Lklapi-Serial");
            String timestamp = LakalaPayCommon.getHeadValue(response, "Lklapi-Timestamp");
            String nonce = LakalaPayCommon.getHeadValue(response, "Lklapi-Nonce");
            String signature = LakalaPayCommon.getHeadValue(response, "Lklapi-Signature");
            String responseStr = IOUtils.toString(response.getEntity().getContent(), LakalaPayUtil.ENCODING);
            log.info("responseStr:{}", responseStr);
            String source = appid + "\n" + lklapiSerial + "\n" + timestamp + "\n" + nonce + "\n" + responseStr + "\n";
            X509Certificate lklCertificate = LakalaPayCommon.loadCertificate(new FileInputStream(new File(LakalaPayUtil.PUBULIC_KEY)));

            boolean verify = LakalaPayCommon.verify(lklCertificate, source.getBytes(LakalaPayUtil.ENCODING), signature);
            if (verify) {
                message.setData(responseStr);
                message.setMessage(Status.success);
                message.setSuccess(true);
                message.setCode("200");
                log.info("验签成功:");

            } else {
                message.setSuccess(false);
                message.setMessage("验签不通过、支付失败，重新支付");
                message.setCode("-1");
                log.info("验签失败:");
                return message;
            }
        } catch (Exception e) {
            message.setSuccess(false);
            message.setData(e.getMessage());
            message.setMessage("查询失败");
            message.setCode("-1");
            log.error("退款失败，原因：{}", e.getMessage());
        }
        return message;
    }

}
